package pers.lws.erp.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import pers.lws.erp.entity.SysRole;
import pers.lws.erp.entity.SysUser;
import pers.lws.erp.entity.vo.LoginUserVO;
import pers.lws.erp.service.ISysRoleService;
import pers.lws.erp.service.ISysUserService;

import java.util.HashSet;
import java.util.List;

/**
 * @author liuws
 * @create 2020-09-03 15:16
 */
public class LoginUserRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //查询条件
        QueryWrapper<SysUser> loginUserQueryWrapper = new QueryWrapper<>();
        loginUserQueryWrapper.eq("user_name", principal);
        //从数据库查询用户
        SysUser sysUser = sysUserService.getOne(loginUserQueryWrapper);
        //返回一个vo对象
        LoginUserVO loginUserVo = null;
        //判断是否查到
        if (sysUser != null) {
            loginUserVo = new LoginUserVO();
            loginUserVo.setUserId(sysUser.getUserId());
            loginUserVo.setUserName(sysUser.getUserName());
            return new SimpleAuthenticationInfo(
                    loginUserVo,
                    sysUser.getPassword(),
                    ByteSource.Util.bytes(sysUser.getSalt()),
                    this.getName());
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入shiro授权！！");
        // 获取主身份信息
        LoginUserVO login = (LoginUserVO) principalCollection.getPrimaryPrincipal();
        // 获取用户信息
        List<SysRole> rolesByUserId = sysRoleService.findRolesByUserId(login.getUserId());

        //用户角色列表
        HashSet<String> roles = new HashSet<String>();
        if (rolesByUserId.size() != 0) {
            //把角色放入集合，用来添加权限
            rolesByUserId.forEach(role -> roles.add(role.getRoleName()));
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }
}
